# $language = "python"
# $interface = "1.0"


import time, os


class FileOps(object):

    def __init__(self):
        self.now_time = time.strftime("%Y%m%d-%H%M%S", time.localtime())
        self.error_log = 'errorlog%s' % now_time

    @staticmethod
    def read_file():
        # 读取txt设备登陆信息，分割每行数据组成一个list
        with open('huawei_device_list.txt', 'r') as f:
            info = f.read().split('\n')
        # 遍历list，使用#注释该行数据，返回一个生成器
        for i in info:
            if i[0] == '#':
                pass
            elif i == ' ':
                pass
            else:
                yield i.split()

    def write_file(self, error_device):
        # 记录异常设备，写入txt
        with open(self.error_log, 'a') as f:
            f.write(str(error_device) + ' failed.\n')


class Huawei(object):

    def __init__(self, hostname, ip, user, passwd):
        self.hostname = hostname
        self.ip = ip
        self.user = user
        self.passwd = passwd
        # 构造ssh登陆参数，设备名称、用户名、密码、IP地址
        self.cmd = '/SSH2 /L %s /PASSWORD %s /C 3DES /M MD5 %s' % (self.user, self.passwd, self.ip)

    def get_config(self):
        # 调用crt连接，ssh登陆设备
        crt.Session.Connect(self.cmd)
        crt.Screen.Synchronous = True
        # 创建日志文件，开启日志记录功能，日志文明名称格式：设备名称_ip.txt
        crt.Session.LogFileName = '.%scfg%s%s%s%s_%s' % (os.sep, os.sep, now_time, os.sep,self.hostname,
                                                        self.ip)
        crt.Session.Log(True)
        # 执行'dis cu'命令，获取设备配置
        crt.Screen.Send("dis cu" + chr(13))
        # 处理分屏问题，判读是否捕获到关键字符串‘---- More ----’最长等待时间5s，如果捕获该值，发送换行字符串；
        # 如果没有捕获该值认为没有分屏，跳出循环，断开连接
        while True:
            if crt.Screen.WaitForString("---- More ----", 5):
                crt.Screen.Send(' ' + chr(10))
            else:
                break
        crt.Session.Disconnect()


now_time = time.strftime("%Y%m%d-%H%M%S", time.localtime())


def main():
    # 登录设备，备份配置，问题设备写入log文件
    for user_info in FileOps().read_file():

        try:
            device = Huawei(*user_info)
            device.get_config()
        except:
            FileOps().write_file(user_info)

main()

